package org.myy.learn.hot.二叉树.对称二叉树;


import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;

@Slf4j
public class Solution {
    public static boolean isSymmetric(TreeNode root) {
        return check(root, root);
    }

    public static boolean check(TreeNode nodeA, TreeNode nodeB){
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(nodeA);
        queue.offer(nodeB);
        while (!queue.isEmpty()){

            TreeNode u = queue.poll();
            TreeNode v = queue.poll();
            //ToDo && >> 需要满足全部   ||  >>  满足一条就执行
            if (u == null && v == null){continue;}
            if (u == null || v == null || (u.val != v.val)){return false;}  //ToDo 要结合 if (u == null && v == null){continue;}一起看

            //这里只管入队，null在外部判断
            queue.offer(u.left);
            queue.offer(v.right);

            queue.offer(u.right);
            queue.offer(v.left);
        }
        return true;
    }

    private static TreeNode buildTree(Integer[] values){
        if (values == null || values.length == 0){return null;}

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < values.length){
            TreeNode node = queue.poll();

            //左节点
            if(index < values.length && values[index] != null){
                node.left = new TreeNode(values[index]);
                queue.offer(node.left);
            }
            index++;

            //右节点
            if(index < values.length && values[index] != null){
                node.right = new TreeNode(values[index]);
                queue.offer(node.right);
            }
            index++;

        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] values = new Integer[]{1,2,2,3,4,4,3};
        TreeNode root = buildTree(values);
        boolean flag = isSymmetric(root);
        log.info("执行结束，是否对称={}", flag);
    }
}
